package com.yunke.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

/**
 * 云科MyBatis Plus配置类
 * 
 * @author yunke
 * @since 1.0.0
 */
@Configuration
public class YunkeMybatisPlusConfig {

    /**
     * MyBatis Plus拦截器配置
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    /**
     * 元数据自动填充处理器
     */
    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new YunkeMetaObjectHandler();
    }

    /**
     * 云科元数据处理器
     */
    public static class YunkeMetaObjectHandler implements MetaObjectHandler {

        @Override
        public void insertFill(MetaObject metaObject) {
            LocalDateTime now = LocalDateTime.now();
            // 自动填充创建时间
            this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, now);
            // 自动填充更新时间
            this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, now);
            // 自动填充逻辑删除字段
            this.strictInsertFill(metaObject, "deleted", Integer.class, 0);
            
            // TODO: 后续可以从当前登录用户上下文获取用户ID
            // 自动填充创建者
            this.strictInsertFill(metaObject, "createBy", Long.class, 1L);
            // 自动填充更新者
            this.strictInsertFill(metaObject, "updateBy", Long.class, 1L);
        }

        @Override
        public void updateFill(MetaObject metaObject) {
            // 自动填充更新时间
            this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
            
            // TODO: 后续可以从当前登录用户上下文获取用户ID
            // 自动填充更新者
            this.strictUpdateFill(metaObject, "updateBy", Long.class, 1L);
        }
    }
} 